<!--
 * @Author: Coder_Yang
 * @description: 
 * @LastEditTime: 2025-02-20 11:58:17
-->
<template>
  <div>
    <div class="">
      <el-upload
        class="upload-demo"
        action=""
        :on-change="handleChange"
        :on-remove="handleRemove"
        :on-exceed="handleExceed"
        :limit="limitUpload"
        ref="upload"
        accept="application/vnd.openxmlformats-    
        officedocument.spreadsheetml.sheet,application/vnd.ms-excel"
        :auto-upload="false">
          <el-button size="small" type="primary">点击上传</el-button>
      </el-upload>
      <el-button
        @click="exportClick"
        type="primary"
        size="small"
        style="margin: 0 20px"
        icon="el-icon-folder-opened"
        >导出</el-button
      >
    </div>
    <div>
      <el-table 
          :data="tableData" 
          style=" width: 100%; overflow-y: auto;height: 500px;"
          id="mainTable"
          >

        <el-table-column prop="title1" label="label1" width="150" height="200">
        </el-table-column>
        <el-table-column prop="title2" label="label2" width="150" height="200">
        </el-table-column>
        <el-table-column label="配送信息">
          <el-table-column prop="name" label="姓名" width="120">
          </el-table-column>
          <el-table-column label="地址">
            <el-table-column prop="province" label="省份" width="120">
            </el-table-column>
            <el-table-column prop="city" label="市区" width="120">
            </el-table-column>
            <el-table-column prop="address" label="地址" width="300">
            </el-table-column>
            <el-table-column prop="zip" label="邮编" width="120">
            </el-table-column>
          </el-table-column>
        </el-table-column>
      </el-table>
    </div>
    
  </div>
</template>
<script>
import * as XLSX from "xlsx";
import FileSaver from "file-saver";
export default {
  data() {
    return {
      limitUpload:99,
      fileTemp:{},
      tableData:[]
    }
  },
  methods: {
    handleChange(file, fileList){
          console.log(file);
          this.readExcel(file);
          // this.fileTemp = file.raw;
          // if(this.fileTemp){
          //     if((this.fileTemp.type == 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') 
          //         || (this.fileTemp.type == 'application/vnd.ms-excel')){
          //         this.importfxx(this.fileTemp);
          //     } else {
          //         this.$message({
          //             type:'warning',
          //             message:'附件格式错误，请删除后重新上传！'
          //         })
          //     }
          // } else {
          //     this.$message({
          //         type:'warning',
          //         message:'请上传附件！'
          //     })
          // }
      },
       // 读取数据
      readExcel(file) {
        let that = this;
        if (!file) {
          //如果没有文件
          return false;
        } else if (!/.(xls|xlsx)$/.test(file.name.toLowerCase())) {
          this.$message.error("上传格式不正确，请上传xls或者xlsx格式");
          return false;
        }
        const fileReader = new FileReader();
        fileReader.onload = (ev) => {
          try {
            const data = ev.target.result;
            const workbook = XLSX.read(data, {
              type: "binary",
            });
            if (workbook.SheetNames.length >= 1) {
              this.$message({
                message: "导入数据表格成功",
                showClose: true,
                type: "success",
              });
            }
            const wsname = workbook.SheetNames[0]; //取第一张表
            const ws = XLSX.utils.sheet_to_json(workbook.Sheets[wsname]); //生成json表格内容
            console.log("生成json：", ws);

            // that.tableData = [];
            for (var i = 2; i < ws.length; i++) {
              let sheetData = {
                // 键名为绑定 el 表格的关键字，值则是 ws[i][对应表头名]
                date: ws[i]["日期"],
                name: ws[i]["配送信息"],
                province: ws[i]["__EMPTY"],
                city: ws[i]["__EMPTY_1"],
                address: ws[i]["__EMPTY_2"],
                zip: ws[i]["__EMPTY_3"],
              };
              // console.log("上传的数据:", sheetData);
              //添加到表格中
              that.tableData.push(sheetData);
              
              
              //正常导入需要拿到上传的数据就在这从新弄个数组push进去，然后传给后台，后台保存后查询表格返给前端。
            }
            this.$refs.upload.value = "";
            console.log(that.tableData);
          } catch (e) {
            console.log(e);
            return false;
          }
        };
        // 如果为原生 input 则应是 files[0]
        fileReader.readAsBinaryString(file.raw);
      },
      //超出最大上传文件数量时的处理方法
      handleExceed(){
          this.$message({
              type:'warning',
              message:'超出最大上传文件数量的限制！'
          })
          return;
      },
      //移除文件的操作方法
      handleRemove(file,fileList){
          this.fileTemp = null
      }, 
      importfxx(obj) {
        let _this = this;
        let inputDOM = this.$refs.inputer;
        // 通过DOM取文件数据

        this.file = event.currentTarget.files[0];

        var rABS = false; //是否将文件读取为二进制字符串
        var f = this.file;

        var reader = new FileReader();
        //if (!FileReader.prototype.readAsBinaryString) {
        FileReader.prototype.readAsBinaryString = function(f) {
            var binary = "";
            var rABS = false; //是否将文件读取为二进制字符串
            var pt = this;
            var wb; //读取完成的数据
            var outdata;
            var reader = new FileReader();
            reader.onload = function(e) {
                var bytes = new Uint8Array(reader.result);
                var length = bytes.byteLength;
                for (var i = 0; i < length; i++) {
                    binary += String.fromCharCode(bytes[i]);
                }
                //此处引入，用于解析excel
                var XLSX = require("xlsx");
                if (rABS) {
                    wb = XLSX.read(btoa(fixdata(binary)), {
                    //手动转化
                    type: "base64"
                    });
                } else {
                    wb = XLSX.read(binary, {
                    type: "binary"
                    });
                }
                outdata = XLSX.utils.sheet_to_json(wb.Sheets[wb.SheetNames[0]]); 
                //outdata就是读取的数据（不包含标题行即表头，表头会作为对象的下标）
                //此处可对数据进行处理
                let arr = [];
                outdata.map(v => {
                    let obj = {}
                    obj.code = v['Code']
                    obj.name = v['Name']
                    obj.pro = v['province']
                    obj.cit = v['city']
                    obj.dis = v['district']
                    arr.push(obj)
                });
                _this.da=arr;
                _this.dalen=arr.length;
                return arr;
            };
            reader.readAsArrayBuffer(f);
        };
        if (rABS) {
            reader.readAsArrayBuffer(f);
        } else {
            reader.readAsBinaryString(f);
        }
    },
    //导出
    exportClick() {
      //第一个参数是到处后文件名，第二个是id绑定表格dom
      // this.exportExcel("test", "mainTable");
      this.$router.push({
        name: 'formDetails',
      })
    },
    //转换数据
    exportExcel(filename, tableId) {
      var xlsxParam = { raw: true }; // 导出的内容只做解析，不进行格式转换
      var table = document.querySelector("#" + tableId).cloneNode(true);
      var wb = XLSX.utils.table_to_book(table, xlsxParam);
      /* 获取二进制字符进行输出 */
      var wbout = XLSX.write(wb, {
        bookType: "xlsx",
        bookSST: true,
        type: "array",
      });
      try {
        FileSaver.saveAs(
          new Blob([wbout], { type: "application/octet-stream" }),
          filename + ".xlsx"
        );
      } catch (e) {
        if (typeof console !== "undefined") {
          console.log(e, wbout);
        }
      }
      return wbout;
    },
  },
  created: function () {

  }
}
</script>

<style scoped>

</style>